<template>
  <div>
    <el-row>
      <el-col style="width:270px">
        <video id="video1" width="260" height="195" autoplay></video>
        <el-col>
        <p v-if="!hasFace" style="font-size: 10px; height: 8px; color: #f56c6c">
          &nbsp;&nbsp;&nbsp;<i class="fa fa-question-circle" aria-hidden="true"></i
          >&nbsp;检测失败！请调整位置！
        </p>
        <p v-else style="font-size: 10px; height: 8px; color: #67c23a">
          &nbsp;&nbsp;&nbsp;<i class="fa fa-question-circle" aria-hidden="true"></i
          >&nbsp;检测成功！请保持不动！
        </p>
      </el-col>
      </el-col>
      <el-col style="width:270px">
        <div>
          <canvas id="canvas1" width="260" height="195"></canvas>
        </div>
        <div style="margin-left: 65px" v-if="!isUploaded">
          <el-button type="primary" @click="uploadImg" :disabled="!isTaking">上传</el-button>
          <el-button type="primary" @click="isTaking = false" :disabled="!isTaking">重新拍照</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
require("tracking/build/tracking-min.js");
require("tracking/build/data/face-min.js");
require("tracking/build/data/mouth-min.js");
require("tracking/examples/assets/stats.min.js");
var _this;
export default {
  data() {
    return {
      localStream: {}, //视频流
      getUserMedia: {}, //调用摄像头
      trackItem: {}, //人脸检测
      hasFace: false, //是否有人脸
      isTaking: false, //是否正在拍照
      isUploaded: false, //是否已上传图片
      formData: {}, //上传数据
    };
  },
  created() {
    _this = this;
  },
  methods: {
    //调用摄像头
    openCamera() {
      this.getUserMedia =
        navigator.getUserMedia ||
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia ||
        navigator.msGetUserMedia;

      this.getUserMedia.call(
        navigator,
        {
          audio: false,
          video: true,
        },
        (stream) => {
          document.getElementById("video1").srcObject = stream;
          _this.localStream = stream;
          _this.TrackFace();
        },
        (error) => {
          // 处理媒体流创建失败错误
          _this.$message.error("打开摄像头失败！");
          console.log("getUserMedia error: " + error);
        }
      );
    },
    // 人脸检测
    TrackFace() {
      let tracker = new tracking.ObjectTracker("face");
      tracker.setInitialScale(1);
      tracker.setStepSize(1);
      tracker.setEdgesDensity(0.1);

      this.trackItem = tracking.track("#video1", tracker, {});

      tracker.on("track", (event) => {
        if (event.data.length > 0) {
          _this.hasFace = true;
          if (!_this.isTaking) {
            setTimeout(function () {
              _this.checkFace();
            }, 1500);
          }
        } else {
          _this.hasFace = false;
        }
      });
    },
    //拍照
    checkFace() {
      if (_this.hasFace && !this.isTaking) {
        _this.drawPicture();
      }
    },
    //拍照具体实现
    drawPicture() {
      let canvas1 = document.getElementById("canvas1");
      let context1 = canvas1.getContext("2d");
      let video1 = document.getElementById("video1");
      context1.drawImage(video1, 0, 0, 260, 195);
      var dataurl = canvas1.toDataURL("image/png", 0.8);

      this.formData = new FormData();
      this.formData.append("image", _this.getFile(dataurl, "image/png"));
      this.isTaking = true;
    },
    //上传图片
    uploadImg() {
      if (this.formData.get("image") !== null) {
        console.log(this.formData);
        _this.$post("/file/uploadimg", this.formData).then((res) => {
          if (res.code === 0) {
            _this.$message.success(res.msg);
            _this.saveLog(res.data);
          } else {
            _this.$message.error(res.msg);
          }
        });
        _this.destoryStream();
      }
    },
    //上传登录日志
    saveLog(url) {
      console.log(url);
      this.isUploaded = true;
      this.$emit('nextStep',url)
    },
    // base64 转文件
    getFile(dataURI, type) {
      let arr = dataURI.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let bytes = window.atob(arr[1]); // 解码base64
      let n = bytes.length;
      let ia = new Uint8Array(n);
      while (n--) {
        ia[n] = bytes.charCodeAt(n);
      }
      return new File([ia], new Date().getTime() + ".png", { type: mime });
    },
    //关闭
    destoryStream() {
      if (_this.localStream instanceof MediaStream) {
         _this.localStream.getTracks()[0].stop();
      }
      _this.localStream = {}
      _this.trackItem = {};
      Object.assign(this.$data, this.$options.data())
    },
  },
};
</script>

<style scoped></style>
